import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid, ENUMS } from '../../stores/definitions';
import { t } from '@lingui/macro';
import { Button, Dialog, Form, Message } from '@alifd/next';
import { observer } from 'mobx-react-lite';
import TicketInfoTable from './TicketInfoTable';
import DrawerFooter from '@/components/DrawerFooter';
import { observable } from 'mobx';
import { useStore } from '@/hooks';
import AttachmentPanel from '../AttachmentPanel';

const FromItem = Form.Item;

const TaskInfo = ({ modal, orderId, isEditModal, onCancel, onSubmit }) => {
  const [formData] = useState(() => observable({}));
  const { scTaskStore: store } = useStore();
  const [ticketsInfos, setTicketsInfos] = useState([]);
  const editCtx = useRef({ origin: {}, changed: {} }).current;

  useEffect(() => {
    if (modal?.[0] === 'viewTask' || modal?.[0] === 'edit') {
      (async () => {
        const task = await store.getTaskInfo(orderId);
        transferTrips(task);
        editCtx.origin = _.cloneDeep(task);
        _.assign(formData, task);
      })();
    }
  }, []);

  function transferTrips(result) {
    const { tickets = [], orderBaseModel = {} } = result;
    const { startMainAreaText, endMainAreaText } = orderBaseModel;
    const cloneTickets = _.cloneDeep(tickets);
    const uniqueArr = store.uniqueArray(cloneTickets);
    setTicketsInfos(() => uniqueArr.map((p) => ({ ...p, startMainAreaText, endMainAreaText })));
  }

  const handleCancel = () => {
    if (!_.isEmpty(editCtx.changed)) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(formData, name, value);
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleCopyTrip = async () => {
    try {
      const text = await store._copyTrip(toJS(formData));
      await navigator.clipboard.writeText(text);
      Message.success({ content: t`行程已复制！` });
    } catch (err) {
      console.error('行程复制失败: ', err);
    }
  };

  const handleCopyDispatch = async () => {
    try {
      const text = await store._copyDispatch(toJS(formData));
      await navigator.clipboard.writeText(text);
      Message.success({ content: t`派车已复制！` });
    } catch (err) {
      console.error('派车复制失败: ', err);
    }
  };

  return (
    <Form
      inline
      isPreview={!isEditModal}
      value={formData}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={
        (
          <div style={{ display: 'flex', alignItems: 'center' }}>
            {t`基本信息`}
            {ENUMS._dispatch_states[toJS(formData)?.state] && <Button text type="primary" style={{ marginLeft: 10, fontWeight: 500 }} onClick={handleCopyDispatch}>{t`复制派车信息`}</Button>}
          </div>
        )}
      />
      <FieldsGrid
        formData={formData}
        mode="view"
        fields={['id', 'state', 'crDate', 'cancelTime', 'carrierCompanyName', 'driverInfo[0].name', 'driverInfo[0].phone', 'driverInfo[0].licenseNo', 'carrierPrice', 'fleetSettlement', 'driverServiceFee', 'driverSettlement', 'dispatchRemarks']}
      />
      <TitleGrid title={(
        <div style={{ display: 'flex', alignItems: 'center' }}>
          {t`行程信息`}
          <Button text type="primary" style={{ marginLeft: 10, fontWeight: 500 }} onClick={handleCopyTrip}>{t`复制行程信息`}</Button>
        </div>
      )}
      />
      <FieldsGrid
        formData={formData}
        mode="view"
        fields={[
          'departureTime',
        ]}
      />
      {ticketsInfos.map((p) => (
        <FieldsGrid
          formData={p}
          mode="view"
          fields={[
            'startMainAreaText', 'fromStationAddress', 'endMainAreaText', 'toStationAddress',
          ]}
        />
      ))}

      <TitleGrid title={t`上下车详情`} />
      <FieldsGrid
        formData={formData}
        mode="view"
        fields={['startRecord', 'endRecord']}
      />
      <TitleGrid title={t`车票信息`} />
      <TicketInfoTable dataSource={formData.tickets} />
      <TitleGrid title={t`备注`} />
      <FieldsGrid
        formData={formData}
        mode={isEditModal ? 'edit' : 'view'}
        fields={['remark', 'dispatchOrderRemarks', 'cancelRemark']}
      />
      <AttachmentPanel state={formData} />
      <DrawerFooter>
        <FromItem>
          {isEditModal && <Form.Submit validate type="primary" onClick={() => onSubmit(formData)}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};

export default observer(TaskInfo);
